import  React,{Component} from 'react';

class NEditor extends Component {

    static defaultProps = {
        path: '/ueditor/',
        ready:(instance)=>{}
    }

    constructor(props) {
        super(props);
        this.state = {
            editorContent: '',
            defaultValue: props.value,
            randomId: `editor_${(Math.random() * 100000000000000000)}`,
            instance: null,
            config : {
                initialFrameHeight: 600,
                scaleEnabled:false,
                serverUrl:'/uploader/ueditor/server'
            },
        };
    }

    componentDidMount() {
        if (window.UE !== undefined) {
            // 如果全局对象存在，说明编辑器代码已经初始化完成，直接加载编辑器
            this.initEditor();
        } else {
            // 如果全局对象不存在，说明编辑器代码还没有加载完成，需要加载编辑器代码
            this.insertScriptTag();
        }
    }

    insertScriptTag() {
        const loading = [];
        const self = this;
        let configScriptTag = document.getElementById('configScriptTag');
        let editorScriptTag = document.getElementById('editorScriptTag');
        // 如果这个tag不存在，则生成相关代码tag以加载代码
        if (configScriptTag === null) {
            loading.push(new Promise((resolve, reject) => {
                configScriptTag = document.createElement('script');
                configScriptTag.type = 'text/javascript';
                configScriptTag.src = `${self.props.path}neditor.config.js`;
                configScriptTag.id = 'configScriptTag';
                if (configScriptTag.readyState) {
                    configScriptTag.onreadystatechange = () => {
                        if (configScriptTag.readyState === 'loaded' || configScriptTag.readyState === 'complete') {
                            configScriptTag.onreadystatechange = null;
                            resolve(configScriptTag);
                        }
                    };
                } else {
                    configScriptTag.onload = () => {
                        resolve(configScriptTag);
                    };
                }
                configScriptTag.onerror = () => {
                    reject(Error('Configuration load error!'));
                };
                document.body.appendChild(configScriptTag);
            }));
        }
        if (editorScriptTag === null) {
            loading.push(new Promise((resolve, reject) => {
                editorScriptTag = document.createElement('script');
                editorScriptTag.type = 'text/javascript';
                editorScriptTag.src = `${self.props.path}neditor.all.js`;
                editorScriptTag.id = 'editorScriptTag';
                if (editorScriptTag.readyState) {
                    editorScriptTag.onreadystatechange = () => {
                        if (editorScriptTag.readyState === 'loaded' || editorScriptTag.readyState === 'complete') {
                            editorScriptTag.onreadystatechange = null;
                            resolve(editorScriptTag);
                        }
                    };
                } else {
                    editorScriptTag.onload = () => {
                        resolve(editorScriptTag);
                    };
                }
                editorScriptTag.onerror = () => {
                    reject(Error('Editor load error!'));
                };
                document.body.appendChild(editorScriptTag);
            }));
        }
        // 等待代码加载完成后初始化编辑器
        Promise.all(loading).then(() => {
            setTimeout(() => {
                self.initEditor();
            }, 300);
        });
    }



    initEditor() {
        const self = this;
        if (self.state.instance === null) {
            // Vue 异步执行 DOM 更新，这样一来代码执行到这里的时候可能 template 里面的 script 标签还没真正创建
            // 所以，我们只能在 nextTick 里面初始化 UEditor
            setTimeout(()=>{
                self.setState({
                    instance:window.UE.getEditor(self.state.randomId, self.state.config),
                })
                // 绑定事件，当 UEditor 初始化完成后，将编辑器实例通过自定义的 ready 事件交出去
                self.state.instance.addListener('contentChange', () => {
                    self.props.onChange( self.state.instance.getContent())
                });
                self.state.instance.addListener('ready', () => {
                    self.state.instance.setContent(self.state.defaultValue);
                    self.props.ready(self.state.instance);
                });
            },0)
        }
    }

    componentWillUnmount(){

    }

    onChange = (content) => {
        this.props.onChange(content);
    }

    getContent = () => {
        return this.state.editorContent;
    }

    setContent = (content) => {
        setTimeout(()=>{
            this.state.instance.setContent(content)
        },300)
    }

    // initEditor() {
    //     const elem = this.refs.editorElem;
    //     const editor = new E(elem);
    //     // 使用 onchange 函数监听内容的变化，并实时更新到 state 中
    //     editor.customConfig.onchange = (html) => {
    //         this.setState({
    //             editorContent: html,
    //         });
    //         this.onChange(html);
    //     };
    //     editor.customConfig.uploadFileName = 'files[]';
    //     editor.customConfig.uploadImgServer = '/api/upload/editor';
    //     editor.customConfig.uploadImgParams = {token: sessionStorage.getItem('access_token')};
    //     editor.customConfig.zIndex = 100;
    //     editor.create();
    //     this.state.editor = editor;
    //     this.state.editor.txt.html(this.state.editorContent);
    // }

    render() {
        return (
            <div id={this.state.randomId} style={{width:'100%'}} name="content" type="text/plain"/>
        );
    }
}

export default NEditor;
